export const useStorageState = <T>(
    key: string,
    config: {
        defaultValue: T
        afterInit?: (value: T) => void
        removeCondition?: (value: T) => boolean
    },
) => {
    const [state, setState] = useState<T>(config.defaultValue)

    const _setState = (value: T) => {
        setState(value)
        if (config.removeCondition?.(value)) {
            storage.removeItem(`session:${key}`)
            return
        }
        storage.setItem(`session:${key}`, value)
    }

    useEffect(() => {
        storage.getItem<T>(`session:${key}`).then((value) => {
            if (value === null) {
                setState(config.defaultValue)
                config.afterInit?.(config.defaultValue)
                return
            }
            setState(value)
            config.afterInit?.(value)
        })
    }, [key])

    return [state, _setState] as const
}
